﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DevExpress.XtraEditors;
using System.Windows.Forms;
using System.Data;
using System.ComponentModel;

namespace ProgNetDxComponents.Controls.Editors
{
    [ToolboxItem(false)]
    //public class MultiLookUpEditPopupContainerControl : UserControl
    public class MultiLookUpEditPopupContainerControl : PopupContainerControl
    {
        public MultiLookUpEditPopupContainerControl()
        {
            InitializeComponent();
        }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                foreach (MultiEditBaseTab tab in Tabs.Values)
                {
                    tab.Dispose();
                }
            }
            Tabs.Clear();
            tabControl.TabPages.Clear();
            base.Dispose(disposing);
        }

        private string _Separator = "|";
        public string Separator
        {
            get { return _Separator; }
            set { _Separator = value; }
        }

        private PanelControl panelBottom;
        private SimpleButton btnCancel;
        private SimpleButton btnOK;
        private DevExpress.XtraTab.XtraTabControl tabControl;
        private Dictionary<string, MultiEditBaseTab> Tabs = new Dictionary<string, MultiEditBaseTab>();
        
        private void InitializeComponent()
        {
            this.panelBottom = new DevExpress.XtraEditors.PanelControl();
            this.btnCancel = new DevExpress.XtraEditors.SimpleButton();
            this.btnOK = new DevExpress.XtraEditors.SimpleButton();
            this.tabControl = new DevExpress.XtraTab.XtraTabControl();
            ((System.ComponentModel.ISupportInitialize)(this.panelBottom)).BeginInit();
            this.panelBottom.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.tabControl)).BeginInit();
            this.SuspendLayout();
            // 
            // panelBottom
            // 
            this.panelBottom.Controls.Add(this.btnCancel);
            this.panelBottom.Controls.Add(this.btnOK);
            this.panelBottom.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.panelBottom.Location = new System.Drawing.Point(0, 179);
            this.panelBottom.Name = "panelBottom";
            this.panelBottom.Size = new System.Drawing.Size(304, 28);
            this.panelBottom.TabIndex = 0;
            // 
            // btnCancel
            // 
            this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnCancel.DialogResult = DialogResult.Cancel;
            this.btnCancel.Location = new System.Drawing.Point(256, 4);
            this.btnCancel.Name = "btnCancel";
            this.btnCancel.Size = new System.Drawing.Size(40, 19);
            this.btnCancel.TabIndex = 1;
            this.btnCancel.Text = "Cancel";
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            // 
            // btnOK
            // 
            this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnOK.DialogResult = DialogResult.OK;
            this.btnOK.Location = new System.Drawing.Point(210, 4);
            this.btnOK.Name = "btnOK";
            this.btnOK.Size = new System.Drawing.Size(40, 19);
            this.btnOK.TabIndex = 0;
            this.btnOK.Text = "OK";
            this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
            // 
            // tabControl
            // 
            this.tabControl.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabControl.Location = new System.Drawing.Point(0, 0);
            this.tabControl.Name = "tabControl";
            this.tabControl.Size = new System.Drawing.Size(304, 179);
            this.tabControl.TabIndex = 1;
            // 
            // MultiLookUpEditPopupContainerControl
            // 
            this.Controls.Add(this.tabControl);
            this.Controls.Add(this.panelBottom);
            this.Name = "MultiLookUpEditPopupContainerControl";
            this.Size = new System.Drawing.Size(304, 207);
            ((System.ComponentModel.ISupportInitialize)(this.panelBottom)).EndInit();
            this.panelBottom.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.tabControl)).EndInit();
            this.ResumeLayout(false);

        }

        public void AddGridTab(DataTable dt, string ValueMember, string DisplayMember, string filter, string tabCode, string tabName)
        {
            MultiEditViewControl tab = new MultiEditViewControl();
            AddTab(tab, dt, ValueMember, DisplayMember, filter, tabCode, tabName);
        }

        public void AddTreeTab(DataTable dt, string ValueMember, string DisplayMember, string ParentFieldName, string filter, string tabCode, string tabName)
        {
            MultiEditTreeControl tab = new MultiEditTreeControl();
            tab.ParentFieldName = ParentFieldName;
            AddTab(tab, dt, ValueMember, DisplayMember, filter, tabCode, tabName);
        }

        private void AddTab(MultiEditBaseTab tab, DataTable dt, string ValueMember, string DisplayMember, string filter, string tabCode, string tabName)
        {
            if (!string.IsNullOrEmpty(tabCode) && !Tabs.ContainsKey(tabCode))
            {
                tab.RowSelected += new EventHandler<RowSelectEventArgs>(tab_RowSelected);
                Tabs.Add(tabCode, tab);
                tab.ValueMember = ValueMember;
                tab.DisplayMember = DisplayMember;
                tab.DataSource = dt;
                tab.Filter = filter;
                tab.Name = tabCode;
                tab.Text = tabName;
                tabControl.TabPages.Add(tab);
            }
        }

        void tab_RowSelected(object sender, RowSelectEventArgs e)
        {
            MultiEditBaseTab tab = sender as MultiEditBaseTab;
            SetOwnerEditValue(tab, e.Row);
        }
        
        private void SetOwnerEditValue(MultiEditBaseTab tab, DataRow r)
        {
            if (tab != null && OwnerEdit != null)
            {
                if (r != null)
                    OwnerEdit.EditValue = tab.Name + Separator + r[tab.ValueMember].ToString();
                else
                    OwnerEdit.EditValue = "";
            }
            else if (OwnerEdit != null)
                OwnerEdit.EditValue = "";
            if (OwnerEdit != null && OwnerEdit.IsPopupOpen)
                OwnerEdit.ClosePopup();
        }

        public void RemoveTab(string tabCode)
        {
            if (Tabs.ContainsKey(tabCode))
            {
                if (tabControl.TabPages.Contains(Tabs[tabCode]))
                {
                    tabControl.TabPages.Remove(Tabs[tabCode]);
                }
                Tabs.Remove(tabCode);
            }
        }

        public void ClearTabs()
        {
            foreach (KeyValuePair<string, MultiEditBaseTab> kvp in Tabs)
            {
                if (tabControl.TabPages.Contains(kvp.Value))
                {
                    tabControl.TabPages.Remove(kvp.Value);
                    kvp.Value.Dispose();
                }
            }
            Tabs.Clear();
        }

        public MultiEditBaseTab GetTab(string tabCode)
        {
            if (!string.IsNullOrEmpty(tabCode) && Tabs.ContainsKey(tabCode))
            {
                return Tabs[tabCode];
            }
            return null;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            MultiEditBaseTab tab = tabControl.SelectedTabPage as MultiEditBaseTab;
            SetOwnerEditValue(tab, tab.GetSelectedRow());
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            OwnerEdit.CancelPopup();
        }

        internal void SelectItem(object editValue)
        {
            if (editValue != null && !string.IsNullOrEmpty(editValue.ToString()))
            {
                string val = editValue.ToString();
                int idx = val.IndexOf(Separator);
                if (idx > -1)
                {
                    string tabCode = val.Substring(0, idx);
                    string value = val.Substring(idx + Separator.Length);
                    MultiEditBaseTab tab = GetTab(tabCode);
                    if (tab != null)
                    {
                        tabControl.SelectedTabPage = tab;
                        DataTable dt = tab.DataSource as DataTable;
                        Type t = typeof(string);
                        if (dt != null)
                        {
                            if (dt.Columns.Contains(tab.ValueMember))
                            {
                                t = dt.Columns[tab.ValueMember].DataType;
                            }
                        }
                        object focusVal = value;
                        if (t != typeof(string))
                        {
                            try
                            {
                                focusVal = Convert.ChangeType(focusVal, t);
                            }
                            catch { }
                        }
                        tab.FocusValue(focusVal);
                    }
                }
            }
            else
            {
                if (tabControl.TabPages.Count > 0)
                {
                    MultiEditBaseTab tab = tabControl.TabPages[0] as MultiEditBaseTab;
                    if (tab != null)
                    {
                        tabControl.SelectedTabPage = tab;
                    }
                    foreach (MultiEditBaseTab t in Tabs.Values)
                        t.FocusValue(null);
                }

            }
        }

        internal string GetDisplayValue(object editValue)
        {
            string result = "";
            if (editValue != null && !string.IsNullOrEmpty(editValue.ToString()))
            {
                string tabCode = GetTabCodeFromValue(editValue);
                string value = GetRealValueFromValue(editValue);
                    result = value;
                    MultiEditBaseTab tab = GetTab(tabCode);
                    if (tab != null)
                    {
                        if (tab.ValueMember != tab.DisplayMember && tab.DataSource != null)
                        {
                            DataRow r = tab.DataSource.SelectFirstRow(tab.ValueMember + " = " + value.EscapeSql());
                            if (r != null)
                            {
                                result = r[tab.DisplayMember].ToString();
                            }
                        }
                    }
            }
            return result;
        }

        internal string GetTabCodeFromValue(object editValue)
        {
            string result = "";
            if (editValue != null && !string.IsNullOrEmpty(editValue.ToString()))
            {
                string val = editValue.ToString();
                int idx = val.IndexOf(Separator);
                if (idx > -1)
                {
                    result = val.Substring(0, idx);
                }
            }
            return result;
        }
        internal string GetRealValueFromValue(object editValue)
        {
            string result = "";
            if (editValue != null && !string.IsNullOrEmpty(editValue.ToString()))
            {
                string val = editValue.ToString();
                int idx = val.IndexOf(Separator);
                if (idx > -1)
                {
                    result = val.Substring(idx + Separator.Length);
                }
            }
            return result;
        }
    }

}
